<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="股票代码" prop="stockCode">
        <el-input
          v-model="queryParams.stockCode"
          placeholder="请输入股票代码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="策略分组" prop="strategyGroupId">
        <el-select v-model="queryParams.strategyGroupId" placeholder="请选择策略分组" clearable>
          <el-option
            v-for="dict in strategyGroupList"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>


      <el-form-item label="策略ID" prop="strategyId">
        <el-input
          v-model="queryParams.strategyId"
          placeholder="请输入策略ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="策略名称" prop="strategyName">
        <el-input
          v-model="queryParams.strategyName"
          placeholder="请输入策略名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>


      <el-form-item label="交易所" prop="exchange">
        <el-select v-model="queryParams.exchange" placeholder="请输入交易所" clearable>
          <el-option label="沪市" :value="0"/>
          <el-option label="深市" :value="1"/>
        </el-select>
      </el-form-item>

      <el-form-item label="触发类型" prop="triggerType">
        <el-select v-model="queryParams.triggerType" placeholder="请选择触发类型" clearable>
          <el-option label="自动开仓" value="AUTO_TAKE_POSITION_TRIGGER"/>
          <el-option label="静态止盈" value="STATIC_STOP_PROFIT_TRIGGER"/>
          <el-option label="静态止损" value="STATIC_STOP_LOSS_TRIGGER"/>
          <el-option label="动态止损" value="DYNAMIC_STOP_LOSS_TRIGGER"/>
          <el-option label="动态止盈" value="DYNAMIC_STOP_PROFIT_TRIGGER"/>
          <el-option label="定时平仓" value="TIME_CLOSE_POSITION_TRIGGER"/>
        </el-select>
      </el-form-item>

      <el-form-item label="平仓状态" prop="positionClosed">
        <el-select v-model="queryParams.positionClosed" placeholder="请输入平仓状态" clearable>
          <el-option label="否" :value="0"/>
          <el-option label="是" :value="1"/>
        </el-select>
      </el-form-item>


      <el-form-item label="交易日期" prop="createDate">
        <el-date-picker clearable size="small" style="width: 200px"
                        v-model="queryParams.createDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择交易日期日期">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="仓号" prop="delegateCode">
        <el-input
          v-model="queryParams.delegateCode"
          placeholder="请输入仓号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:record:add']"
        >买入
        </el-button>
      </el-col>

      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="warning"-->
      <!--          plain-->
      <!--          icon="el-icon-download"-->
      <!--          size="mini"-->
      <!--          @click="handleExport"-->
      <!--          v-hasPermi="['system:record:export']"-->
      <!--        >导出</el-button>-->
      <!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recordList">
      <!--      <el-table-column type="selection" width="55" align="center" />-->
      <el-table-column label="策略分组名" align="center" width="90" prop="strategyGroupId" :formatter="strategyGroupFormat"/>
      <el-table-column label="策略ID" align="center" prop="strategyId"/>
      <el-table-column label="策略名称" align="center" prop="strategyName"/>
      <el-table-column label="订单编号" width="310" align="center" prop="orderNo"/>
      <el-table-column label="股票代码" width="200" align="center" prop="stockCode"/>
      <el-table-column label="交易所" align="center" prop="exchange">
        <template slot-scope="scope">
          <span v-if="scope.row.exchange == 0">沪市</span>
          <span v-if="scope.row.exchange == 1">深市</span>
        </template>
      </el-table-column>
      <el-table-column label="委托类型" align="center" prop="delegateType">
        <template slot-scope="scope">
          <span v-if="scope.row.delegateType === 0">普通买入</span>
          <span v-if="scope.row.delegateType === 1">普通卖出</span>
          <span v-if="scope.row.delegateType === 2">信用卖出</span>
          <!--          <span v-if="scope.row.delegateType == 3">深市</span>-->
          <!--          <span v-if="scope.row.delegateType == 4">深市</span>-->
          <!--          <span v-if="scope.row.delegateType == 5">深市</span>-->
          <!--          <span v-if="scope.row.delegateType == 6">深市</span>-->
          <!--          <span v-if="scope.row.delegateType == 7">深市</span>-->
          <!--          <span v-if="scope.row.delegateType == 8">深市</span>-->

        </template>
      </el-table-column>
      <!--      <el-table-column label="委托状态" align="center" prop="delegateState" />-->

      <el-table-column label="委托状态" align="center" prop="delegateState">
        <template slot-scope="scope">
          <span v-if="scope.row.delegateState === 0">未申报</span>
          <span v-if="scope.row.delegateState === 1">正在申报</span>
          <span v-if="scope.row.delegateState === 2">已申报</span>
          <span v-if="scope.row.delegateState === 3">已报待撤</span>
          <span v-if="scope.row.delegateState === 4">部成待撤</span>
          <span v-if="scope.row.delegateState === 5">部撤</span>
          <span v-if="scope.row.delegateState === 6">已撤</span>
          <span v-if="scope.row.delegateState === 7">部分成交</span>
          <span v-if="scope.row.delegateState === 8">已成交</span>
          <span v-if="scope.row.delegateState === 9">废单</span>
          <span v-if="scope.row.delegateState === 10">错误</span>
          <span v-if="scope.row.delegateState === 11">其他未知</span>

        </template>
      </el-table-column>
      <el-table-column label="触发类型" align="center" prop="triggerType">
        <template slot-scope="scope">
          <span v-if="scope.row.triggerType == 'AUTO_TAKE_POSITION_TRIGGER'">自动开仓</span>
          <span v-if="scope.row.triggerType == 'STATIC_STOP_PROFIT_TRIGGER'">静态止盈</span>
          <span v-if="scope.row.triggerType == 'STATIC_STOP_LOSS_TRIGGER'">静态止损</span>
          <span v-if="scope.row.triggerType == 'DYNAMIC_STOP_LOSS_TRIGGER'">动态止损</span>
          <span v-if="scope.row.triggerType == 'DYNAMIC_STOP_PROFIT_TRIGGER'">动态止盈</span>
          <span v-if="scope.row.triggerType == 'TIME_CLOSE_POSITION_TRIGGER'">定时平仓</span>
        </template>
      </el-table-column>
      <el-table-column label="委托价格" align="center" prop="price"/>
      <el-table-column label="成交价格" align="center" prop="dealPrice"/>
      <el-table-column label="成交数量" align="center" prop="dealVolume"/>
      <el-table-column label="成交金额" align="center" prop="dealAmount"/>
      <el-table-column label="委托股数" align="center" prop="delegateVolume"/>
      <el-table-column label="仓号" align="center" width="300" prop="delegateCode"/>
      <el-table-column label="撤单委托 " align="center" prop="delegateCancle">
        <template slot-scope="scope">
          <span v-if="scope.row.delegateCancle === true">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>
      <el-table-column label="单据状态" align="center" prop="tradingStatus">
        <template slot-scope="scope">
          <span v-if="scope.row.tradingStatus === 0">交易失败</span>
          <span v-if="scope.row.tradingStatus === 1">交易成功</span>
        </template>
      </el-table-column>
      <el-table-column label="失败消息 " width="100" align="center" prop="errorMsg"/>
      <el-table-column label="平仓收益金额 " width="100" align="center" prop="profit"/>
      <el-table-column label="收益率 " align="center" prop="profitRate"/>
      >
      <el-table-column label="撤单数量" align="center" prop="delegateCancleVolume"/>
      <el-table-column label="委托时间" width="200" align="center" prop="createTime"/>
      <!--      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
      <!--        <template slot-scope="scope">-->
      <!--          <el-button-->
      <!--            size="mini"-->
      <!--            type="text"-->
      <!--            icon="el-icon-edit"-->
      <!--            @click="handleCancelUpdate(scope.row)"-->
      <!--            v-hasPermi="['system:record:edit']"-->
      <!--          >撤单</el-button>-->
      <!--          <el-button-->
      <!--            size="mini"-->
      <!--            type="text"-->
      <!--            icon="el-icon-sell"-->
      <!--            @click="handleSellUpdate(scope.row)"-->
      <!--            v-hasPermi="['system:record:edit']"-->
      <!--          >卖出</el-button>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加交易记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="交易所" prop="exchange">
          <el-select v-model="form.exchange" placeholder="选择交易所">
            <el-option label="沪市" :value="0"/>
            <el-option label="深市" :value="1"/>
          </el-select>
        </el-form-item>
        <el-form-item label="股票代码" prop="stockCode">
          <el-input v-model="form.stockCode" placeholder="请输入股票代码"/>
        </el-form-item>

        <el-form-item label="价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入价格"/>
        </el-form-item>
        <el-form-item label="委托股数" prop="delegateVolume">
          <el-input v-model="form.delegateVolume" placeholder="请输入委托股数"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 卖出对话框 -->
    <el-dialog :title="sellTitle" :visible.sync="sellopen" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入价格"/>
        </el-form-item>
        <el-form-item label="卖出股数" prop="delegateVolume">
          <el-input v-model="form.delegateVolume" placeholder="请输入委托股数"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="sellSubmitForm">确 定</el-button>
        <el-button @click="sellCancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 撤单对话框 -->
    <el-dialog :title="cancelTitle" :visible.sync="cancleopen" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="撤单数量" prop="delegateCancleVolume">
          <el-input v-model="form.delegateCancleVolume" placeholder="请输入撤单数量"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cancelSubmitForm">确 定</el-button>
        <el-button @click="cancelcancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listRecord, getRecord, delRecord, addRecord, updateRecord, cancleOrder} from "@/api/business/record";
import {getDicts} from "@/api/system/dict/data";

export default {
  name: "Record",
  data() {
    return {

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 交易记录表格数据
      recordList: [],
      // 弹出层标题
      title: "",
      sellTitle: "",
      cancelTitle: "",

      // 是否显示弹出层
      open: false,
      cancleopen: false,
      sellopen: false,
      strategyGroupList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        cusNo: null,
        stockholderNo: null,
        stockCode: null,
        strategyId: null,
        strategyGroupId: null,
        strategyName: null,
        exchange: null,
        positionClosed: null,
        triggerType: null,
        createDate: null,
        delegateType: null,
        delegateState: null,
        price: null,
        dealPrice: null,
        dealVolume: null,
        delegateVolume: null,
        delegateCode: null,
        tradingStatus: null,
        delegateCancle: null,
        delegateCancleVolume: null,
        delegateTime: null,
        errorMsg: null,
        createUser: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        stockCode: [
          {required: true, message: "股票代码不能为空", trigger: "blur"}
        ],
        exchange: [
          {required: true, message: "交易所：0：沪市 1：深市不能为空", trigger: "blur"}
        ],
        delegateType: [
          {required: true, message: "委托类型: 0:普通买入 1：普通卖出 不能为空", trigger: "change"}
        ],
        delegateState: [
          {required: true, message: "委托状态不能为空", trigger: "blur"}
        ],
        price: [
          {required: true, message: "价格不能为空", trigger: "blur"}
        ],
        delegateVolume: [
          {required: true, message: "委托股数不能为空", trigger: "blur"}
        ],
        tradingStatus: [
          {required: true, message: "交易状态(0:成功 1：失败)不能为空", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    this.getStrategyGroupList();
    this.getList();
  },
  methods: {
    /** 查询交易记录列表 */
    getList() {
      this.loading = true;
      listRecord(this.queryParams).then(response => {
        this.recordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    strategyGroupFormat(row) {
      return this.selectDictLabel(this.strategyGroupList, row.strategyGroupId);
    },
    /** 查询策略组别列表 */
    async getStrategyGroupList() {
      await getDicts("business_strategy_group").then(response => {
        console.log("strategyGroupList:", response)
        this.strategyGroupList = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    sellCancel() {
      this.sellopen = false;
      this.reset();
    },
    cancelcancel() {
      this.cancleopen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        cusNo: null,
        stockholderNo: null,
        stockCode: null,
        exchange: null,
        delegateType: null,
        delegateState: null,
        price: null,
        dealPrice: null,
        dealVolume: null,
        delegateVolume: null,
        delegateCode: null,
        tradingStatus: 0,
        delegateCancle: null,
        delegateCancleVolume: null,
        delegateTime: null,
        errorMsg: null,
        createTime: null,
        createUser: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "买入委托";
    },
    /** 卖出委托*/
    handleSellUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getRecord(id).then(response => {
        this.form = response.data;
        this.sellopen = true;
        this.sellTitle = "卖出委托";
      });
    },

    /** 撤单委托 */
    handleCancelUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getRecord(id).then(response => {
        this.form = response.data;
        this.cancleopen = true;
        this.cancelTitle = "撤单委托";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.delegateType = 0
          addRecord(this.form).then(response => {
            this.$modal.msgSuccess("委托买入成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 卖出按钮 */
    sellSubmitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.delegateType = 1
          this.form.delegateCancleVolume = 0
          addRecord(this.form).then(response => {
            this.$modal.msgSuccess("委托卖出成功");
            this.sellOpen = false;
            this.getList();
          });
        }
      });
    },
    /** 撤单按钮 */
    cancelSubmitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          cancleOrder(this.form).then(response => {
            this.$modal.msgSuccess("撤单操作成功");
            this.cancleopen = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除交易记录编号为"' + ids + '"的数据项？').then(function () {
        return delRecord(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/record/export', {
        ...this.queryParams
      }, `record_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
